<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <div class="title">
      <el-tag>操作步骤说明：</el-tag>
      <el-tag>第一步：点击新增，填写能耗数据</el-tag>
      <el-tag>
        第二步：点击本页面{{ deptLevel == 0 ? "上报" : "汇总" }}按钮，进行上报
      </el-tag>
      <el-tag type="danger">
        注：上报后发现数据错误，①上级部门没有审核可以点击撤回按钮调整，②如已审核点击纠正按钮调整，③如最上级部门已汇总则无法再调整
      </el-tag>
    </div>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      border
      :height="620"
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :yearAndmonth="yearAndmonth"
      :visible.sync="show"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import { getInfo } from "@/api/login";
import {
  getLedgerlist,
  deleteLedger,
  reportLedger,
  collectLedgerself,
  recallLedger,
} from "@/api/standingbook/newstandingbook.js";
import operate from "@/views/work/accounts/newadd/components/operate.vue";
import correct from "@/views/work/accounts/newadd/components/correct.vue";
import back from "@/views/work/accounts/newadd/components/back.vue";
export default {
  name: "",
  components: {
    operate,
    correct,
    back,
  },
  dicts: ["ledger_report_status", "ledger_audit_status"],
  data() {
    return {
      deptLevel: null,
      yearAndmonth: {},
      //弹窗
      id: "",
      modelName: "",
      show: false,
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            year: {
              label: "年份:",
              typeName: "el-date-picker",
              type: "year",
              size: "small",
              placeholder: "选择年份",
              "value-format": "yyyy",
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增",
              type: "primary",
              typeName: "el-button",
              plain: true,
              size: "small",
              icon: "el-icon-plus",
              click: () => this.showModel("operate"),
            },
            {
              label: "全年",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-s-data",
              click: this.handlerAllyear,
            },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            prop: "deptName",
            label: "单位名称",
            minWidth: 300,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let that = this;
              let name = scope.row.deptName;
              let a = (
                <router-link
                  to={
                    "/work/standbook/newadds/add?id=" +
                    scope.row.id +
                    "&year=" +
                    scope.row.year +
                    "&month=" +
                    scope.row.month +
                    "&disabled=1" +
                    "&createTime=" +
                    scope.row.createTime
                  }
                  class="link-type"
                >
                  {name}
                </router-link>
              );
              return <div>{a}</div>;
            },
          },
          {
            prop: "year",
            label: "年份",
            width: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "",
            label: "填报类型",
            width: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let that = this;
              return <div>月报</div>;
            },
          },
          {
            prop: "",
            label: "填报日期",
            width: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let that = this;
              let a = scope.row.year ?? "";
              let b = scope.row.month ?? "";
              let c = a + b;
              return h("div", c);
            },
          },
          {
            prop: "statisticEmployee",
            label: "录入人员",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "createTime",
            label: "录入时间",
            width: 180,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "updateTime",
            label: "更新时间",
            width: 180,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "ledgerReportStatus",
            label: "上报状态",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.ledger_report_status}
                    value={scope.row.ledgerReportStatus}
                  />
                </div>
              );
            },
          },
          {
            prop: "ledgerAuditStatus",
            label: "审核状态",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.ledger_audit_status}
                    value={scope.row.ledgerAuditStatus}
                  />
                </div>
              );
            },
          },
          {
            prop: "specialSituationDescription",
            label: "备注",
            align: "center",
            minWidth: 120,
            showOverflowTooltip: true,
          },
          {
            label: "操作",
            width: 280,
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let aName = "";
              let isCorrectionLedger = scope.row.isCorrectionLedger; // 0 非纠正数据 1纠正数据
              if (that.deptLevel == 0) {
                if (isCorrectionLedger == 0) {
                  aName = "上报";
                } else if (isCorrectionLedger == 1) {
                  aName = "纠正上报";
                }
              } else if (that.deptLevel == 1 || that.deptLevel == 2) {
                if (isCorrectionLedger == 0) {
                  aName = "汇总";
                } else if (isCorrectionLedger == 1) {
                  aName = "纠正汇总";
                }
              }
              let a, b, c, d, e, f, g;
              let ledgerReportStatus = scope.row.ledgerReportStatus;
              let ledgerAuditStatus = scope.row.ledgerAuditStatus;
              let ledgerStatus = scope.row.ledgerStatus; // 台账省报状态
              switch (ledgerStatus) {
                // 台账未上报
                case 0:
                  a = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-upload2"
                      onClick={() => {
                        that.collectOrrequest(scope.row.id);
                      }}
                    >
                      {aName}
                    </el-button>
                  );
                  c = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-edit"
                      onClick={() => {
                        that.$router.push({
                          name: "newaddAdd",
                          query: {
                            id: scope.row.id,
                            year: scope.row.year,
                            month: scope.row.month,
                            disabled: "0",
                            correct: isCorrectionLedger.toString(),
                          },
                        });
                      }}
                    >
                      编辑
                    </el-button>
                  );
                  if (isCorrectionLedger == 0) {
                    d = (
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-delete"
                        onClick={() => {
                          that.handlerDelete(scope.row);
                        }}
                        class="text-danger"
                      >
                        删除
                      </el-button>
                    );
                  }
                  break;
                // 台账待审核
                case 1:
                  e = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-download"
                      onClick={() => {
                        that.handlerCheckback(scope.row);
                      }}
                    >
                      撤回
                    </el-button>
                  );
                  break;
                // 台账待汇总
                case 2:
                  // 最高级没有汇总
                  if (that.deptLevel != 2) {
                    f = (
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-check"
                        onClick={() => {
                          that.showModel("correct", scope.row);
                        }}
                      >
                        纠正
                      </el-button>
                    );
                  }
                  break;
                // 台账退回
                case 3:
                  g = (
                    <el-button
                      type="text"
                      size="small"
                      icon="el-icon-check"
                      class="text-danger"
                      onClick={() => {
                        that.showModel("back", scope.row);
                      }}
                    >
                      确认退回
                    </el-button>
                  );
                  break;
                // 台账已汇总
                case 4:
                  // 最高级没有汇总
                  if (that.deptLevel != 2) {
                    f = (
                      <el-button
                        type="text"
                        size="small"
                        icon="el-icon-check"
                        onClick={() => {
                          that.showModel("correct", scope.row);
                        }}
                      >
                        纠正
                      </el-button>
                    );
                  }
                  break;
                // 数据导出
                case 5:
                  break;
              }
              b = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  onClick={() => {
                    that.$router.push({
                      name: "newaddAdd",
                      query: {
                        id: scope.row.id,
                        year: scope.row.year,
                        month: scope.row.month,
                        disabled: "1",
                        createTime: scope.row.createTime,
                      },
                    });
                  }}
                >
                  查看
                </el-button>
              );
              return (
                <div style="display: flex;align-items: center;justify-content: flex-start;">
                  {a}
                  {b}
                  {c}
                  {g}
                  {d}
                  {e}
                  {f}
                </div>
              );
            },
          },
        ],
        data: [],
      },
    };
  },
  created() {
    this.getDeptLevel();
  },
  mounted() {
    this.handlerSearchDetail();
  },
  methods: {
    async getDeptLevel() {
      const res = await getInfo();
      this.deptLevel = res.user.deptLevel;
    },
    async initData(data) {
      let that = this;
      let query = {
        ...data,
      };
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await getLedgerlist(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          that.tableData.data = arr;
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 搜索
    handlerSearchDetail() {
      // const { ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      if (data.year) {
        data.year = data.year + "年";
      }
      data.deptId = this.$store.state.user.deptId;
      this.initData(data);
    },

    // 重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    handlerAllyear() {
      let time = new Date().getFullYear();
      // this.$refs?.form?.setFieldValue("year", time.toString());
      // this.pageSize = 12;
      this.$router.push({
        name: "accountsDetail",
        query: {},
      });
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handlerDelete(row) {
      let that = this;
      let id = row.id;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.delectRequest(id);
        })
        .catch(() => {
          that.$message({
            message: "取消删除",
          });
        });
    },
    delectRequest(id) {
      let that = this;
      deleteLedger(id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            this.handlerSearchDetail();
            return false;
          }
          that.$message.success("已删除!");
          that.handlerSearchDetail();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!401005");
        });
    },
    // 上报or汇总
    collectOrrequest(id) {
      let params = {
        ledgerIds: [],
      };
      params.ledgerIds.push(id);
      let cname = "";
      if (this.deptLevel == 0) {
        cname = "上报";
      } else if (this.deptLevel == 1 || this.deptLevel == 2) {
        cname = "汇总";
      }
      const text = "是否确认" + cname + "该条数据" + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          if (this.deptLevel == 0) {
            // "上报";
            this.requestReport(params);
          } else if (this.deptLevel == 1 || this.deptLevel == 2) {
            // "汇总";
            this.requestCollect(params);
          }
        })
        .catch(() => {
          this.$message({
            message: "取消",
          });
        });
    },
    //上报请求
    requestReport(params) {
      reportLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            this.handlerSearchDetail();
            return false;
          }
          this.$message.success("已上报!");
          this.handlerSearchDetail();
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 汇总请求
    requestCollect(params) {
      collectLedgerself(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            this.handlerSearchDetail();
            return false;
          }
          this.$message.success("已汇总!");
          this.handlerSearchDetail();
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handlerCheckback(row) {
      let that = this;
      let cmName = "";
      cmName = "撤回";
      const text = "是否确认" + cmName + "数据" + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.requestcorrectLedger(row);
        })
        .catch(() => {
          that.$message({
            message: "取消" + cmName,
          });
        });
    },
    requestcorrectLedger(row) {
      let params = {
        ledgerIds: [],
      };
      params.ledgerIds.push(row.id);
      this.requestRecall(params);
    },
    // 撤回
    requestRecall(params) {
      recallLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            this.handlerSearchDetail();
            return false;
          }
          this.$message.success("已撤回!");
          setTimeout(() => {
            this.handlerSearchDetail();
          }, 200);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 弹窗
    showModel(name, params) {
      this.modelName = name;
      this.id = params?.id || "";
      this.yearAndmonth = {
        year: params?.year,
        month: params?.month,
      };
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .title {
  .el-tag {
    margin-right: 10px !important;
    margin-bottom: 20px;
  }
}
</style>
